<?php
declare (strict_types=1);

namespace app\command;

use app\model\OrderModel;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;

class ModifyData extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('modifydata')
            ->setDescription('the modifydata command');
    }

    protected function execute(Input $input, Output $output)
    {
        $objReader     = IOFactory::createReader('Xlsx');
        $filename      = "20250115.xlsx";
        $objPHPExcel   = $objReader->load(root_path() . '/public/' . $filename);//传入的文件
        $sheet         = $objPHPExcel->getSheet(0);   //excel中的第一张sheet
        $highestRow    = $sheet->getHighestRow();       // 取得总行数
        $highestColumn = $sheet->getHighestColumn();   // 取得总列数
        \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn);
        $lines = $highestRow - 1;
        if ($lines <= 0) {
            return json(['code' => 0, 'message' => '没有数据！']);
        }
        $data = [];
        for ($j = 2; $j <= $highestRow; $j++) {
            $goods_info_one   = [];
            $is_combine       = false;
            $next_order_sn    = '';
            $data['order_sn'] = $objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue();
            $next_order_sn    = $objPHPExcel->getActiveSheet()->getCell("A" . ($j + 1))->getValue();
            $next_goods_info  = $objPHPExcel->getActiveSheet()->getCell("Q" . ($j + 1))->getValue();
            $m                = 0;

            if (empty($next_order_sn)) {  // 组合
                // 找到不为空的
                $m    = 1;
                $flag = true;
                do {
                    $order_sn = $objPHPExcel->getActiveSheet()->getCell("A" . ($j + $m + 1))->getValue();
                    if (!empty($order_sn) || $j >= $highestRow) {
                        $flag = false;
                        break;
                    }
                    $m++;
                    if ($m >= 5) {
                        $flag = false;
                        break;
                    }
                } while ($flag);

                for ($n = 1; $n <= $m; $n++) {
                    $index          = $j + $n;
                    $goods_info     = $objPHPExcel->getActiveSheet()->getCell("Q" . $index)->getValue();
                    if ($goods_info) {
                        $goods_info = trim($goods_info);
                        $one            = $this->parseSexCnt($goods_info);
                        $goods_info_one = array_merge($goods_info_one, $one);
                    }
                }
                if (!empty($next_goods_info)) $is_combine = true;
            }

            $data['order_sn']          = trim($data['order_sn']);
//            $data['amount']            = trim($objPHPExcel->getActiveSheet()->getCell("C" . $j)->getValue());
//            $data['order_create_time'] = trim($objPHPExcel->getActiveSheet()->getCell("G" . $j)->getValue());
//            $data['customer']          = trim($objPHPExcel->getActiveSheet()->getCell("I" . $j)->getValue());
//            $data['mobile']            = trim($objPHPExcel->getActiveSheet()->getCell("J" . $j)->getValue());
//            $data['address']           = trim($objPHPExcel->getActiveSheet()->getCell("K" . $j)->getValue());
//            $data['address']           = preg_replace('/[^a-zA-Z0-9\p{Han}\/\-\.]/u', '', $data['address']);
            $is_exists = OrderModel::where('order_sn', trim($data['order_sn']))->find();
            if (!$is_exists) {
                if (strpos($data['address'], "中国") !== false) {
                    $data['type']    = 1;
                    $data['address'] = tecent_address_parse($data['address']);
                } else {    // 不包含
                    $data['type'] = 2;
                }
            }

            $goods_info = trim($objPHPExcel->getActiveSheet()->getCell("Q" . $j)->getValue());
            $result     = $this->parseSexCnt($goods_info);
            if ($is_combine) {
                $data['is_combine'] = 1;
                $result             = array_merge($result, $goods_info_one);
            } else {
                $data['is_combine'] = 0;
            }
//            $res                 = $this->parseSexCntArr($result);
//            if ($is_exists) {
//                $data['pink_cnt']    = $res['pink_cnt'];
//                $data['blue_cnt']    = $res['blue_cnt'];
//            }
//            $data['is_lady']     = $res['is_lady'] == false ? 0 : 1;
//            $data['combine_cnt'] = $this->combineCnt($data['pink_cnt'], $data['blue_cnt']);

            //
//            $idcard         = trim($objPHPExcel->getActiveSheet()->getCell("M" . $j)->getValue());
//            $data['idcard'] = $idcard;

            if (!$is_exists) {
                $output->writeln("$j == 订单号不存在：" . $data['order_sn']);
//                OrderModel::create($data);
//                OrderModel::save($data);
            } else {
                $output->writeln("$j == 订单号已存在：" . $data['order_sn']);
                if ($is_combine) {
                    $goods_type_arr = array_column($result, "goods_type");
                    if (!in_array("akg", $goods_type_arr)) {    // 拆成两单
                        foreach ($result as $key=>$tmp_item) {
                            if ($key == 0) {
                                $is_exists->save(['is_combine' => 0, 'blue_cnt'=>$tmp_item['cnt'], 'goods_type'=>$tmp_item['goods_type']]);
                            } else {
                                $new_data = $is_exists->getData();
                                unset($new_data['id']);
                                $new_data['blue_cnt'] = $tmp_item['cnt'];
                                $new_data['goods_type'] = $tmp_item['goods_type'];
                                OrderModel::create($new_data);
                            }
                        }

                    } else {
                        $is_exists->save(['goods_type'=>'akg']);
                    }
                } else {
                    $goods_info     = $objPHPExcel->getActiveSheet()->getCell("Q" . $j)->getValue();
                    $goods_type = $this->getGoodsType($goods_info);
                    $is_exists->save(['goods_type'=>$goods_type]);
                    $output->writeln($is_exists->order_sn . "=====" . $goods_info);
                }

            }
            if ($is_combine) $j += $m;
        }
        // 指令输出
        $output->writeln('modifydata');
    }


    public function parseSexCntArr($arr)
    {
        $result = [
            'pink_cnt' => 0,
            'blue_cnt' => 0,
            'is_lady'  => false
        ];
        if (count($arr) == 1) { // 非组合
            $result['is_lady'] = $arr[0]['is_lady'];
        }
        foreach ($arr as $k => $v) {
            if ($v['is_lady'] == false) {
                $result['blue_cnt'] += $v['cnt'];
            } else {
                $result['pink_cnt'] += $v['cnt'];
            }
        }
        return $result;
    }

    /**
     * 解析数量和性别
     * @param $str
     * @return array
     */
    public function parseSexCnt($str)
    {
        // 判断是男士还是女士
        $isLady = stripos($str, '女士') !== false;
        $gender = $isLady ? '女士' : '男士';

        // 判断商品类型
        $issvip = stripos($str, 'SVIP') !== false;
        $isvip  = stripos($str, 'VIP') !== false;
        $ismb   = stripos($str, 'MB') !== false;

        // 提取数量
        preg_match('/商品数量：(\d+)/', $str, $matchesForQuantity);
        $quantity = isset($matchesForQuantity[1]) ? $matchesForQuantity[1] : 0;
        if ($issvip) {
            $quantity = $quantity * 5;
        } else if ($isvip) {
            $quantity = $quantity * 3;
        }

        $goods_type = $this->getGoodsType($str);
        return [['is_lady' => $isLady, 'cnt' => $quantity, 'goods_type'=>$goods_type]];
    }

    public function getGoodsType($goods_name)
    {
        if (stripos($goods_name, "GnAKG") !== false) {
            return 'akg';
        } elseif (stripos($goods_name, "GnCell") !== false) {
            return 'cell';
        } elseif (stripos($goods_name, "护肤套盒") !== false) {
            return 'hufu';
        } elseif (stripos($goods_name, "招财猫") !== false) {
            return 'zcm';
        }
        return 'akg';
    }

    public function combineCnt($pink_cnt, $blue_cnt)
    {
        if ($blue_cnt == 1 && $pink_cnt == 1) return 1;
        if ($blue_cnt == 2 && $pink_cnt == 1) return 2;
        if ($blue_cnt == 4 && $pink_cnt == 1) return 3;
        if ($blue_cnt == 1 && $pink_cnt == 4) return 4;
        if ($blue_cnt == 1 && $pink_cnt == 2) return 5;
        if ($blue_cnt == 2 && $pink_cnt == 2) return 6;
//        if ($blue_cnt == 0 && $pink_cnt == 5) return 7;
        if ($blue_cnt == 3 && $pink_cnt == 1) return 8;
        if ($blue_cnt == 1 && $pink_cnt == 3) return 9;
        if ($blue_cnt == 2 && $pink_cnt == 3) return 10;
        if ($blue_cnt == 3 && $pink_cnt == 2) return 11;
        if ($blue_cnt == 5 && $pink_cnt == 5) return 12;
//        if ($blue_cnt == 0 && $pink_cnt == 4) return 13;
//        if ($blue_cnt == 4 && $pink_cnt == 0) return 14;
        if ($blue_cnt == 3 && $pink_cnt == 3) return 15;
        if ($blue_cnt == 2 && $pink_cnt == 4) return 16;
        if ($blue_cnt == 4 && $pink_cnt == 4) return 17;
//        if ($blue_cnt == 5 && $pink_cnt == 0) return 18;
        if ($blue_cnt == 5 && $pink_cnt == 1) return 19;
//        if ($blue_cnt == 6 && $pink_cnt == 0) return 20;
        return 0;
    }
}
